const Actions = require('./actions');
const DB = require('app/db.js');
import { guid, getTime, getMarkdownText, sendNotice } from 'clientConfig/util/queryurlfield';
const monStorage = require('clientConfig/util/StoreData').monStorage;
const Storage = require('clientConfig/util/StoreData').Storage;
import { Control } from 'react-keeper';
const { Toast } = SaltUI;

let form_component_values = null;
module.exports = Reflux.createStore({
    listenables: [Actions],
    data: {

    },

    onFetch: function (params, cb) {
        let t = this;
        DB.Approval.get_approval_list({
            module_type: "workplan",
            proj_category: "software",
            status: 8,
            PageNum: 0,
            CountForAPage: 100,
            id: Storage.get('user.id')
        })
            .then((content) => { // 成功
                var proNumAll = [];
                var proNameAll = [];
                var webhookAll = [];
                if (content.list instanceof Array) {
                    content.list.map((item, index) => {
                        var obj = {}
                        obj.value = index;
                        obj.text = item.proj_name;
                        obj.folder_id = item.folder_id;
                        obj.finish_time = item.finish_time instanceof Array ? [].concat([item.create_time], item.finish_time) : [item.create_time, item.finish_time];
                        proNameAll.push(obj);
                        proNumAll.push(item.proj_num);
                        webhookAll.push(item.proj_webhook);
                    })
                }
                t.data.proNumAll = proNumAll
                t.data.proNameAll = proNameAll
                t.data.webhookAll = webhookAll
                t.updateComponent();
            })
            .catch((error) => { // 失败 or 有异常被捕获

            });
    },
    onSendForm: function (params, paypointerNum, ohterData, boo) {
        let t = this;
        let agent_id = Storage.get('user.agentid');
        let create_time = getTime();
        let finish_time = "";
        let originator_user = monStorage.get('user.nickname');
        let originator_user_id = Storage.get('user.id');
        let dept_id = monStorage.get('user.department');
        let approvers = ohterData.spr;
        let approvers_id = ohterData.approvers_id;
        let cc_list = ohterData.csr;
        let cc_list_id = ohterData.cc_list_id;
        let folder_id = ohterData.folder_id;
        var array = [];
        if (approvers instanceof Array) {
            for (let i = 0; i < approvers.length; i++) {
                array.push(JSON.stringify({ content: "", file: "", imgae: "" }));
            }
        }
        let process_result = array.length > 1 ? array : JSON.stringify({ content: "", file: "", imgae: "" });
        let next_cursor = 0;
        const status = 1;
        const module_type = "payment";
        const proj_category = !boo ? "payplan" : "changereq";
        const proj_num = params.data.proNum;
        const proj_name = params.data.proName;
        const proj_webhook = ohterData.proj_webhook;
        const proj_markdown = getMarkdownText({ create_time, originator_user, approvers, proj_name, proj_num, status, title: "支付计划" })
        const process_id = guid();
        var nodelists = []
        let node_info = [];
        for (let i = 0; i < params.node.length; i++) {
            var obj = {}
            obj.name = params.node[i].label;
            if (params.node[i].label.indexOf('金额') > -1) {
                if (params.data[params.node[i].name].indexOf('万元') == -1)
                    obj.value = params.data[params.node[i].name] + "万元"
            } else {
                obj.value = params.data[params.node[i].name];
            }
            node_info.push(obj);
        }
        var obj = {}
        node_info.push({ name: "上传附件", value: ohterData.upfileName })
        obj.node_info = node_info
        Object.assign(obj, { node_name: !boo ? "payplan" : "changereq", modified: !boo ? "0" : '1', permission: "1" })
        nodelists.push(obj);
        let pointer = params.data.paypointe1;
        let payAll = {};
        payAll.proportion = params.data.payProportion1;
        if (params.data.proTotalMoney.indexOf("万元") == -1)//金额单位
            payAll.payTotalMoney = params.data.proTotalMoney + "万元";
        if (params.data.proMoney1.indexOf('万元') == -1)//金额单位
            payAll.payMoney = params.data.proMoney1 + "万元"
        if (params.data.paypointe2) {
            pointer += "，" + params.data.paypointe2;
            payAll.proportion += "，" + params.data.payProportion2;
            if (params.data.proMoney2.indexOf('万元') == -1)//金额单位
                payAll.payMoney += "，" + params.data.proMoney2 + "万元"
        }
        payAll = JSON.stringify(payAll)
        form_component_values = {
            content: { finish_time: params.data.finish_time,paypointerNum, payPointerCurrNum: 0, paypointerStrack: 0, payPoniterStatus: '计划同意', proj_name: params.data.proName, proj_num: params.data.proNum, process_id: process_id, paymanage_node: pointer, paymanage_proportion: payAll, proj_create_time: getTime() },
            nodelists: nodelists
        }
        var send = Object.assign({}, { agent_id, create_time, finish_time, originator_user, originator_user_id, dept_id, approvers, approvers_id, cc_list, cc_list_id, folder_id, process_result, next_cursor, status, module_type, proj_category, proj_num, proj_name, proj_webhook, proj_markdown, process_id, form_component_values })
        // console.log(send)
        if (params.pagedata) {
            send = this.modify(send, params);
            //console.log(send)
        }
        let notice_info = {
            "process_id": process_id,
            "proj_num": proj_num,
            "proj_name": proj_name,
            "create_time": create_time,
            "status": status,
            "type": "待我审批的"
        }
        let noticed_lists = approvers_id instanceof Array ? approvers_id[next_cursor] : approvers_id;
        DB.Approval.send_approval(send)
            .then((content) => { // 成功
                Toast.show({
                    type: 'success',
                    content: '你的支付计划已提交'
                });
                sendNotice(noticed_lists, notice_info);
                Control.go(-1)
            })
            .catch((error) => { // 失败 or 有异常被捕获
                if (error.errcode == 2) {
                    Toast.show({
                        type: 'error',
                        content: '该项目的支付计划申请已存在，无需再次提交'
                    });
                } else {
                    Toast.show({
                        type: 'error',
                        content: '提交失败'
                    });
                }
                t.data.loading = false
                t.updateComponent();
            });
    },

    modify: function (new_data, old_data) {
        let edit = old_data.edit;
        old_data = old_data.pagedata;
        let old_change = [];//变更前字段 发送群消息
        let new_change = [];//变更后字段 发送群消息
        let old_data_name = [];//变更前字段名称的数组
        let form_component_values_new = new_data.form_component_values;
        let nodelists_new = form_component_values_new.nodelists;
        old_data.node_info.map((item, index) => {
            old_data_name.push(item.name)
        })
        var old_j = 0
        for (let i = 0; i < nodelists_new.length; i++) {
            let node_info_new = nodelists_new[i].node_info;
            let node_info_old = old_data.node_info;
            for (let j = 0; j < node_info_new.length; j++) {
                if (old_data_name.indexOf(node_info_new[j].name) == -1) {
                    old_j++
                    node_info_new[j].ext_value = '空'//变更过
                    old_change.push('空');
                    new_change.push(node_info_new[j].value);
                } else {
                    if (node_info_new[j].name == node_info_old[j - old_j].name) {
                        if (node_info_new[j].value != node_info_old[j - old_j].value) {
                            node_info_new[j].ext_value = node_info_old[j - old_j].value//变更过
                            old_change.push(node_info_old[j - old_j].value);
                            new_change.push(node_info_new[j].value);
                        }else{
                            node_info_new[j].ext_value = node_info_new[j].value//变更过
                            old_change.push(node_info_new[j].value);
                            new_change.push(node_info_new[j].value);
                        }
                    }
                }
            }
        }
        form_component_values_new.nodelists = nodelists_new;
        form_component_values_new.content.changerecord_type = JSON.stringify({
            type: edit ? "撤销申请" : "内容变更",
            old_process_id: old_data.process_id
        })
        new_data.form_component_values = form_component_values_new;
        let { create_time, originator_user, approvers, next_cursor, proj_name, proj_num, status } = { ...new_data };
        const proj_markdown = getMarkdownText({ old_change, new_change, change_type: edit ? "撤销申请" : "内容变更", create_time, originator_user, approvers: approvers[next_cursor], proj_name, proj_num, status,title: '支付管理' }, "change")
        new_data.proj_markdown = proj_markdown;
        return new_data;
    },
    updateComponent: function () {
        this.trigger(this.data);
    },

    getInitialState: function () {
        return this.data;
    }
});
